import React, { useState, useEffect } from "react";
import styles from "./index.module.less";
import ChatContainer from "@components/chatContainer";
import { useNavigate, useSearchParams } from "react-router-dom";
import { connect } from "react-redux";
import {
    getSingleGoodsIdAction,
    getFirstChatDateAction,
    getContentListAction /* , sendMsgAction */ /* , adviseAtChatWindowAction */ /* , receiveAtChatWindowAction */,
} from "@redux/actions";
import moment from "moment";
import toast from "@utils/showToast";
import socket from "@depjs/globalSocket";
import _ from "lodash";

const ChatWindow = (props) => {
    const {
        getSingleGoodsIdAction,
        singleGoods,
        firstDate,
        getFirstChatDateAction,
        getContentListAction,
        contentList /* , sendMsgAction */ /* , adviseAtChatWindowAction */ /* , receiveAtChatWindowAction, realTime */,
    } = props;

    const navigate = useNavigate();

    const [params] = useSearchParams();
    const goodsId = params.get("goodsId");
    const loginUser = params.get("loginUser");
    const toUser = params.get("toUser");

    const [val, setVal] = useState("");
    const [realTime, setRealTime] = useState({
        goodsId: "",
        loginUser: "",
        chatUser: "",
        isAtChatWindow: false,
    });

    const sendMsg = () => {
        if (!loginUser) {
            toast.fail("请先登录");
            return;
        }

        if (!val.trim()) return;

        const msg = {
            goodsId,
            from: loginUser,
            to: toUser,
            chatId: loginUser + "_" + toUser,
            content: val.trim(),
            isRead: false,
        };

        msg.isRead =
            goodsId === realTime.goodsId &&
            toUser === realTime.loginUser &&
            loginUser === realTime.chatUser &&
            realTime.isAtChatWindow;

        console.log(
            goodsId,
            realTime.goodsId,
            "\n",
            toUser,
            realTime.loginUser,
            "\n",
            loginUser,
            realTime.chatUser,
            "\n",
            realTime.isAtChatWindow
        );

        // sendMsgAction(msg)

        socket.emit("sendMsg", msg);

        setVal("");
    };

    // useEffect(() => {
    //   receiveAtChatWindowAction()
    // }, [receiveAtChatWindowAction])

    useEffect(() => {
        socket.on("connect", () => {
            socket.on("replyAtChatWindow", (msg) => {
                setRealTime(msg);
            });
        });
    }, [setRealTime]);

    useEffect(() => {
        socket.on("connect", () => {
            socket.on("receiveMsg", (msg) => {
                if (
                    goodsId === msg.goodsId &&
                    (loginUser === msg.from || loginUser === msg.to)
                ) {
                    const getContentList = _.once(getContentListAction);
                    getContentList(goodsId, loginUser, toUser);
                }
            });
        });
    }, [getContentListAction, goodsId, loginUser, toUser]);

    useEffect(() => {
        getSingleGoodsIdAction(goodsId);
    }, [getSingleGoodsIdAction, goodsId]);

    useEffect(() => {
        getFirstChatDateAction(goodsId);
    }, [getFirstChatDateAction, goodsId]);

    useEffect(() => {
        loginUser && getContentListAction(goodsId, loginUser, toUser);
    }, [getContentListAction, goodsId, loginUser, toUser]);

    useEffect(() => {
        /**每次收发消息后，都把最新的消息展示出来
         * 就需要内容部分滚动到底部
         */
        window.scrollTo(0, document.body.scrollHeight);
    }, [contentList]);

    useEffect(() => {
        const chatObj = {
            goodsId,
            loginUser,
            chatUser: toUser,
        };

        // adviseAtChatWindowAction({...chatObj, isAtChatWindow: true})
        socket.emit("atChatWindow", { ...chatObj, isAtChatWindow: true });

        return () => {
            // adviseAtChatWindowAction({...chatObj, isAtChatWindow: false})
            socket.emit("atChatWindow", { ...chatObj, isAtChatWindow: false });
        };
    }, [goodsId, loginUser, toUser]);

    return (
        <div className={styles.chat_window}>
            <div className={styles.head}>
                <p
                    className={styles.pre}
                    onClick={() => {
                        navigate(-1);
                    }}
                ></p>
                <p className={styles.chat_nick}>{toUser}</p>
            </div>
            <div className={styles.goods_detail}>
                <div className={styles.left}>
                    <div className={styles.goods_img}>
                        <img
                            src={
                                Object.keys(singleGoods).length > 0
                                    ? singleGoods.goodsImages[0].img
                                    : ""
                            }
                            alt=""
                        />
                    </div>
                    <div className={styles.goods_msg}>
                        <p className={styles.goods_p1}>
                            {singleGoods.brand}/{singleGoods.goodsName}
                        </p>
                        <p className={styles.goods_p2}>
                            {singleGoods.price} G币
                        </p>
                    </div>
                </div>
                <div
                    className={styles.buy_now}
                    style={{
                        display:
                            !singleGoods || loginUser === singleGoods.userName
                                ? "none"
                                : "block",
                    }}
                >
                    立即购买
                </div>
            </div>
            <div className={styles.window_main}>
                <p className={styles.first_date}>
                    {moment(firstDate).format("YYYY-MM-DD HH:mm:ss")}
                </p>
                <ChatContainer
                    contentList={contentList}
                    loginUser={loginUser}
                />
            </div>
            <div className={styles.chat_input}>
                <input
                    type="text"
                    autoComplete="off"
                    value={val}
                    onChange={(e) => {
                        setVal(e.target.value);
                    }}
                    className={val.length > 0 ? styles.dec : ""}
                />
                <div className={styles.expression_icon}></div>
                <button
                    className={`${styles.chat_send} ${
                        val.length > 0 ? styles.add : ""
                    }`}
                    onClick={sendMsg}
                >
                    发送
                </button>
            </div>
        </div>
    );
};

export default connect(
    (state) => ({
        singleGoods: state.getSingleGoodsIdReducer,
        firstDate: state.firstJoinChatReducer,
        contentList: state.contentListReducer,
        // realTime: state.realTimeReadMsgReducer,
    }),
    {
        getSingleGoodsIdAction,
        getFirstChatDateAction,
        getContentListAction /* , sendMsgAction */ /* , adviseAtChatWindowAction */ /* , receiveAtChatWindowAction */,
    }
)(ChatWindow);
